package com.yxplearn.mybatisplus.dao.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.yxplearn.mybatisplus.dao.core.EntryType;
import com.yxplearn.mybatisplus.dao.core.Property;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JdbcUtil<T> {


    private DruidDataSource dataSource;

    public void initDataSource() {
        // 创建Druid数据源
        dataSource = new DruidDataSource();

        // 设置数据源的基本属性
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); // 数据库驱动
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/mybatisplus?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8"); // 数据库URL
        dataSource.setUsername("root"); // 数据库用户名
        dataSource.setPassword("123456"); // 数据库密码

        // 可以设置更多的数据源属性如初始连接数、最大连接数等
        DataSource validDataSource = null;
        try {
            // 初始化数据源
            dataSource.init();
            // 验证数据源是否可用
            validDataSource = dataSource.getConnection() != null ? dataSource : null;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 打印数据源信息
        System.out.println("Druid DataSource initialized successfully: " + (validDataSource != null));
    }

    public Object executeQuery(SqlOperation sqlOperation) {
        PreparedStatement ps;
        ResultSet rs;
        Connection conn;

        try {
            conn = dataSource.getConnection();
            conn.setAutoCommit(true);
            ps = conn.prepareStatement(sqlOperation.getSql());
            sqlOperation.fillAllSqlParams(ps);
            rs = ps.executeQuery();
            if (rs.next()) {
                EntryType entryType = sqlOperation.getEntryType();
                Object t = entryType.getClazz().newInstance();
                for (Object value : entryType.propertiesMap.values()) {
                    Property property = (Property) value;
                    if (property.getField() != null) {
                        property.getValue(rs, t);
                    }
                }
                return t;
            }
            return null;
        } catch (SQLException | InstantiationException | IllegalAccessException s) {
            s.printStackTrace();
        }
        return null;
    }
}
